<template>
  <div class="app-container">
    <div class="zd3" v-loading="webUpload">
      <div class="zd3-title">
				<p>
					<span>章节名称</span>
					<input v-model="title" type="text" placeholder="请输入章节名称" />
				</p>
				<el-button size="small" type="success" @click="getZhangjie">查询</el-button>
        <el-button size="small" @click="resetList">重置</el-button>
        <el-button size="small" type="primary" @click="addHanlderOne">新增章节</el-button>
      </div>
      <div class="zd3-btm">
        <el-table
          :data="tableData"
					border
          v-loading="loading"
          style="width: 100%;border-radius: 8px;"
        >
					<el-table-column type="index" align="center" label="序号" width="80" />
					<el-table-column type="expand">
					  <template slot-scope="props" v-if="props.row.children">
							<el-table :data="props.row.children" border :show-header="false" style="width: 100%">
								<el-table-column align="center" prop="title" label="章节名称"/>
								<el-table-column align="center" width="250" label="操作">
								  <template slot-scope="scope">
										<el-button type="text" size="small" @click="writeTwoClassify(scope.row,props.row)">编辑</el-button>
                    <el-popconfirm placement="top" hideIcon title="是否要删除此行？" @onConfirm="deleterTwoClassify(scope.row)">
                      <el-button type="text" size="small" slot="reference">删除</el-button>
                    </el-popconfirm>
								  </template>
								</el-table-column>
							</el-table>
					  </template>
					</el-table-column>
          <el-table-column align="center" prop="title" label="章节名称"/>
					<el-table-column align="center" width="250" label="操作">
					  <template slot-scope="scope" v-if="!scope.row.currentPage">
              <el-button type="text" size="small" @click="addHanlderTwo(scope.row)" v-if="isLoaded">添加小节</el-button>
							<el-button type="text" size="small" @click="writeOneClassify(scope.row)">编辑</el-button>
              <el-popconfirm placement="top" hideIcon title="是否要删除此行？" @onConfirm="deleterOneClassify(scope.row)">
                <el-button type="text" size="small" slot="reference">删除</el-button>
              </el-popconfirm>
					  </template>
					</el-table-column>
        </el-table>
        <el-pagination
          background
          hide-on-single-page
          layout="prev, pager, next"
          :total="total"
          @prev-click="goPrev"
          @next-click="goNext"
        />
      </div>
    </div>
    <!-- 一级分类 -->
    <el-dialog
      :visible.sync="oneShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="true"
      width="65%"
    >
      <div class="change">
        <p>
          <span>章节名称</span>
          <el-input type="text" v-model="oneClasslist.title" class="userselect" placeholder="请输入章节名称" />
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="oneShow = false">取消</el-button>
        <el-button type="primary" @click="saveOne">保存</el-button>
      </div>
    </el-dialog>
    <!-- 二级分类名称 -->
    <el-dialog
      :visible.sync="twoShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="true"
      width="65%"
    >
      <div class="change">
        <p>
          <span>小节名称</span>
          <el-input type="text" v-model="twoClasslist.title" class="userselect" placeholder="请输入小节名称" />
        </p>
        <p>
          <span>上传视频</span>
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="designUpAvatar"
            :on-progress="uploadVideoProcess"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <el-progress v-if="videoFlag == true" :text-inside="true" :stroke-width="16" :percentage="videoUploadPercent" status="success"></el-progress>
          </el-upload>
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="twoShow = false">取消</el-button>
        <el-button type="primary" @click="saveTwo" v-loading.fullscreen.lock="webUpload">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
let parentId = null,fatherId = null;
import axios from 'axios'
import { addZhangjie,qiantaoList,deleteZhangjie,selectZhangjie,updateZhangjie,addClassHour,updateClassHour,uploadKeshi,selectKeshi,deleteKeshi,deleteKeshiFile } from '@/api/people'
export default {
  data(){
    return{
      tableData:[],
      title: '',  //分类搜索名称
      total: 1,
      loading: false,
      oneClasslist: {},
      videoFlag: false,    //上传组件
      videoUploadPercent: 0,//上传组件
      twoClasslist: {
        free: 0
      },
      oneShow: false,    //一级分类弹框显示
      twoShow: false,    //二级分类弹框显示
      oneTempIndex: -1,  //一级分类增加还是修改标识符
      twoTempIndex: -1,  //一级分类增加还是修改标识符
      isLoaded: true,
      webUpload: false
    }
  },
  mounted(){
    console.log(JSON.parse(this.$route.params.options))
    const tempdata = JSON.parse(this.$route.params.options)
    parentId = tempdata.id
    // const loading = this.$loading({
    //   lock: true,
    //   text: '上传中请稍等...',
    //   spinner: 'el-icon-loading',
    //   background: 'rgba(255, 255, 255, 0.5)'
    // })
    const temp = sessionStorage.getItem('xaiojie')
    console.log(temp)
    if(temp){
      this.isLoaded = false
    }else{
      this.isLoaded = true
    }
    
    this.getZhangjie(tempdata.id)
  },
  methods: {
    /**
     * 搜索
     */
    search(){
      
    },
    // 重置搜索
    resetList(){
      this.title = ''
    },
    /**
     * 获取视频上传进度
     */
    uploadVideoProcess(event, file, fileList){
      console.log(file.percentage)
    },
    /**
     * 获取分类列表
     */
    getZhangjie(id){
      qiantaoList(id).then(res => {
        console.log(res)
        this.tableData = res.data.items
      })
    },
    /**
     * 新增一级分类
     */
    addHanlderOne(){
      this.oneShow = true
      this.oneTempIndex = -1
    },
    /**
     * 新增二级分类
     */
    addHanlderTwo(item){
      console.log(item)
      this.twoShow = true
      this.twoTempIndex = -1
      fatherId = item.id
      this.twoClasslist = {}
      // this.twoClasslist.parentId = item.id
    },
    /**
     * 编辑一级分类
     */
    writeOneClassify(item){
      this.oneShow = true
      this.oneClasslist = {...item}
      this.oneTempIndex = 1
    },
    /**
     * 编辑二级分类
     */
    writeTwoClassify(item1,item2){
      console.log(item1,item2)
      fatherId = item2.id
      this.twoShow = true
      this.twoClasslist = {...item1}
      this.twoTempIndex = 1
    },
    /**
     * 查看视频详情
     */
    lookClass(item){
      this.$router.push({
        name: 'Zhangjie',
        params: {
          options: JSON.stringify(item)
        }
      })
    },
    /**
     * 描述管理
     */
    miaoshu(item){
      this.$router.push({
        name: 'Miaoshu',
        params: {
          options: JSON.stringify(item)
        }
      })
    },
    /**
     * 章节管理
     */
    zhangjie(item){
      this.$router.push({
        name: 'Zhangjieguanli',
        params: {
          options: JSON.stringify(item)
        }
      })
    },
    /**
     * 删除一级分类
     */
    deleterOneClassify(item){
      deleteZhangjie(item.id).then(res => {
        console.log(res)
        this.$message({
          message: res.message,
          type: 'success',
          showClose: true
        })
        this.getZhangjie(parentId)
      })
    },
    /**
     * 删除二级分类
     */
    deleterTwoClassify(item){
      deleteKeshi(item.id).then(res => {
        console.log(res)
        this.$message({
          message: res.message,
          type: 'success',
          showClose: true
        })
        this.getZhangjie(parentId)
      })
    },
    /**
     * 上传视频
     */
    designUpAvatar(item){
      console.log(this.fileNum)
      this.videoFlag = true
      var formData = new FormData()
      // 进度条事件
      const config = {
        onUploadProgress: progressEvent => {
          console.log('progressEvent',progressEvent)
          // progressEvent.loaded:已上传文件大小
          // progressEvent.total:被上传文件的总大小
          this.videoUploadPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(2))
        }
      }
      formData.append("file", item.file)
      axios.post('/jdy-edu/eduservice/edu-video/upload',formData,config).then(res => {
        console.log(res)
        this.$message({
          showClose: true,
          message: '添加成功，后台上传中',
          type: "success"
        })
        this.isLoaded = false
        // this.videoFlag = false
        // 获取到id，根据id获取真实id
        this.getVideoId(res.data.data.videoId)
      }).catch((res) => {
        console.log(res)
      })
    },
    /**
     * 获取videoid,定时获取id,当有id的情况下开始调用修改分类接口
     */
    getVideoId(id){
      let timer = setInterval(() => {
        const videoEndTime = +new Date()
        const videoBeginTime = sessionStorage.getItem('videoUploadTime')
        if(videoEndTime - videoBeginTime*1 > 1200000){
          clearInterval(timer)
          this.isLoaded = true
          this.videoFlag = false
          sessionStorage.removeItem('xaiojie')
          this.$forceUpdate()
        }
        axios.get(`/jdy-edu/eduservice/edu-video/getVid/${id}`).then(res => {
          console.log('真实id',res)
          if(res.data.data.vid){
            console.log('得到真实id',res.data.data.vid)
            // this.twoClasslist.videoSourceId = res.data.data.vid
            const temp = JSON.parse(sessionStorage.getItem('xaiojie'))
            console.log(temp)
            // 获取到缓存的对象开始更新小节
            updateClassHour({
              free: null,
              id: temp.id,
              title: temp.title,
              videoOriginalName: res.data.data.vid
            }).then(res => {
              console.log(res)
              console.log('异步更新小节成功')
              // this.$message({
              //   message: res.message,
              //   type: 'success',
              //   showClose: true
              // })
              // 当更新完成小节之后，把isloaded状态改为true，清除掉缓存，让新增小节功能可以使用
              this.isLoaded = true
              this.videoFlag = false
              sessionStorage.removeItem('xaiojie')
              this.getZhangjie(parentId)
              this.$forceUpdate()
            }).catch(() => {
              sessionStorage.removeItem('xaiojie')
            })
            clearInterval(timer)
          }
        })
      }, 10000);
      
    },
    /**
     * 保存章节编辑结果
     */
    saveOne(){
      if(this.oneTempIndex !== -1){
        this.oneClasslist.courseId = parentId
        updateZhangjie(this.oneClasslist.id,this.oneClasslist).then(res => {
          this.$message({
            message: res.message,
            type: 'success',
            showClose: true
          })
          this.oneShow = false
          this.getZhangjie(parentId)
        })
      }else{
        // console.log(+new Date(),Math.round(Math.random()*1000))
        // 获取不重复得id,当前时间戳数
        const _id = +new Date()
        // 当前id
        this.oneClasslist.id = _id
        // 父级id
        this.oneClasslist.courseId = parentId
        addZhangjie(this.oneClasslist).then(res => {
          console.log(res)
          this.oneShow = false
          this.$message({
            message: res.message,
            type: 'success',
            showClose: true
          })
          this.getZhangjie(parentId)
        })
      }
      
    },
    /**
     * 保存小节编辑结果
     */
    saveTwo(){
      let videoUploadTime = +new Date()
      sessionStorage.setItem('videoUploadTime',videoUploadTime)
      if(this.twoTempIndex !== -1){
        this.webUpload = true
        this.twoClasslist.courseId = parentId
        this.twoClasslist.chapterId = fatherId
        updateClassHour({
          free: null,
          id: this.twoClasslist.id,
          title: this.twoClasslist.title,
          videoOriginalName: this.twoClasslist.videoOriginalName
        }).then(res => {
          console.log(res)
          this.twoShow = false
          this.$message({
            message: res.message,
            type: 'success',
            showClose: true
          })
          this.webUpload = false
          sessionStorage.setItem('xaiojie',JSON.stringify(this.twoClasslist))
          if(!this.videoFlag){
            sessionStorage.removeItem('xaiojie')
          }
          this.getZhangjie(parentId)
        })
      }else{
        this.webUpload = true
        this.twoClasslist.id = +new Date()
        this.twoClasslist.courseId = parentId
        this.twoClasslist.chapterId = fatherId
        addClassHour(this.twoClasslist).then(res => {
          console.log(res)
          this.twoShow = false
          this.$message({
            message: res.message,
            type: 'success',
            showClose: true
          })
          this.webUpload = false
          // 点击保存按钮把父级id跟当前id村缓存,在视频上传完成之后获取缓存,用于修改分类
          sessionStorage.setItem('xaiojie',JSON.stringify(this.twoClasslist))
          // 如果没有点击上传视频则清空缓存
          if(!this.videoFlag){
            sessionStorage.removeItem('xaiojie')
          }
          this.getZhangjie(parentId)
        })
      }
      
    },
    /**
     * 上一页
     */
    goPrev(){

    },
    /**
     * 下一页
     */
    goNext(){

    },
  }
}
</script>

<style scoped lang="scss">

/deep/.el-table--medium td {
  padding: 0px;
}
/deep/.el-table__expanded-cell[class*=cell] {
	padding: 0 0 0 128px;
}
/deep/[data-v-70245f58] .el-button--primary {
  color: #fff;
  background-color: #18a05e !important;
  border-color: #18a05e !important;
}
/deep/.el-button--text {
  color: #00c666 !important;
}
.avatar-uploader{
  flex: 1;
}
.avatar-uploader /deep/.el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatars{
	width: 45px;
	height: 45px;
  margin: 0 auto;
  border: 1px solid #ccc
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
	border: 1px dashed #CCCCCC;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.upload-demo{
  margin: 0 10px;
}
.el-progress {
  position: relative;
  line-height: 1;
  flex: 0.9;
}
.morehandle {
  display: flex;
  flex-direction: column;
}
.morehandle .el-button--text{
  color: #18a05e;
  margin-left: 0;
}
.zd3-title {
	height: 70px;
	display: flex;
	align-items: center;
	padding: 0 20px;
	position: relative;
	background: #ffffff;
	border-radius: 8px;
	border: 1px solid rgba(0, 0, 0, 0.1);

	> p {
		font-size: 14px;
		color: #333;
		margin-right: 20px;

		> span {
			padding-right: 20px;
		}

		> input {
			width: 150px;
			height: 32px;
			// background: #ccc;
			border-radius: 3px;
			border: 1px solid #ccc;
			padding-left: 10px;
			color: #333;
		}
	}

	> h3 {
		// width: 64px;
		height: 32px;
		background: #18a05e;
		border-radius: 3px;
		margin: 0 30px 0 0;
		padding: 0 15px;
		color: #fff;
		font-size: 14px;
		line-height: 32px;
		font-weight: 100;
		text-align: center;
		cursor: pointer;
	}

	> h4 {
		padding: 0 15px;
		height: 32px;
		border-radius: 3px;
		border: 1px solid rgba(0, 0, 0, 0.1);
		color: #333;
		font-size: 14px;
		line-height: 32px;
		font-weight: 100;
		text-align: center;
		cursor: pointer;
	}
}
.zd3-btm /deep/.btn-prev::after {
  content: "";
}
.zd3-btm /deep/.btn-prev::before {
  content: "上一页";
}
.zd3-btm /deep/.btn-next::before {
  content: "下一页";
}
.zd3-btm /deep/.btn-next::after {
  content: "";
}
.zd3-btm /deep/.btn-prev,
.zd3-btm /deep/.btn-next {
  width: 80px;
}
.zd3-btm {
  background: rgba(255, 255, 255, 1);
  border-radius: 8px;
  // border: 1px solid rgba(0, 0, 0, 0.1);
  margin-top: 20px;
  overflow: hidden;
  &-title {
    display: flex;
    align-items: center;
    height: 70px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    background: #ffffff;
    > p {
      text-align: center;
      font-size: 16px;
      color: #333;
    }
  }
  .el-pagination {
		white-space: nowrap;
		padding: 15px 5px;
		color: #303133;
		font-weight: bold;
	}
  .addDate {
    margin: 20px 32px 10px 32px;
    height: 32px;
    border-radius: 3px;
    text-align: center;
    line-height: 32px;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    border: 1px dashed rgba(0, 0, 0, 0.25);
  }
  .el-pagination{
    margin: 15px;
    text-align: right;
  }
  .el-button--text {
    margin: 7px 5px;
  }
}
.change {
  display: flex;
  flex-wrap: wrap;
  > p {
    width: 50%;
    font-size: 14px;
    display: flex;
    align-items: center;
    color: #333;
    /deep/.el-input__inner {
      width: inherit;
      background: none;
      height: 32px;
      // line-height: 32px;
      color: #333;
      border: 1px solid rgba(0, 0, 0, 0.1);
      padding: 0 25px;
    }
    /deep/.el-input__icon {
      line-height: 32px;
    }
    .userselect {
      // max-width: 250px;
      flex: 1;
    }

    > span {
      display: block;
      width: 120px;
      text-align: right;
      padding-right: 15px;
    }
    > input {
      width: inherit;
      flex: 1;
      height: 32px;
      border-radius: 3px;
      border: 1px solid rgba(0, 0, 0, 0.1);
      padding-left: 10px;
      color: #333;
    }
  }
}
</style>